//
//  HState.m
//  TestOCRedux
//
//  Created by Hotacool on 2019/1/17.
//  Copyright © 2019 Hotacool. All rights reserved.
//

#import "HState.h"
#import "objc/runtime.h"

@implementation HState {
    NSMutableDictionary *mReDuXdIcT;
    NSMutableArray *mArRaY;
}
- (instancetype)init {
    self = [super init];
    mReDuXdIcT = [NSMutableDictionary dictionary];
    mArRaY = [NSMutableArray array];
    return self;
}

#pragma mark -- []
- (void)setObject:(id)object forKeyedSubscript:(id < NSCopying >)aKey {
    [mReDuXdIcT setObject:object forKey:aKey];
}
- (id)objectForKeyedSubscript:(id)key {
    return [mReDuXdIcT objectForKey:key];
}
- (void)setObject:(id)anObject atIndexedSubscript:(NSUInteger)index {
    const NSUInteger length = [mArRaY count];
    if(index > length) {
        return;
    }
    if(index == length) {
        [mArRaY addObject:anObject];
    } else {
        [mArRaY replaceObjectAtIndex:index withObject:anObject];
    }
}
- (id)objectAtIndexedSubscript:(NSUInteger)idx {
    if(idx >= [mArRaY count]){
        return nil;
    }
    
    return [mArRaY objectAtIndex:idx];
}

#pragma mark -- copying
- (nonnull id)copyWithZone:(nullable NSZone *)zone {
    HState *state = [[self.class allocWithZone:zone] init];
    state->mReDuXdIcT = [mReDuXdIcT mutableCopy];
    state->mArRaY = [mArRaY mutableCopy];
    unsigned int proCount = 0;
    Ivar *ivars = class_copyIvarList([self class], &proCount);
    for (int i = 0; i < proCount; i++) {
        Ivar ivar = ivars[i];
        const char *name = ivar_getName(ivar);
        NSString *key = [NSString stringWithUTF8String:name];
        if ([key hasSuffix:@"mReDuXdIcT"] || [key hasSuffix:@"mArRaY"]) {
            continue;
        }
        id value = [self valueForKey:key];
        [state setValue:value forKey:key];
    }
    free(ivars);
    return state;
}
@end
